package com.sy.cloud.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.sy.cloud.wechat.entity.AccessToken;
import com.sy.cloud.wechat.model.Wxuser;
import com.sy.cloud.wechat.service.ConfigService;
import com.sy.common.service.IDbService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by mac on 2017/11/9.
 */
@Controller
@Slf4j
@RequestMapping("/wapi")
@ResponseBody
public class ApiController {

    @Autowired
    private ConfigService configService;

    @Resource
    private IDbService dbService;
    public void getAccessToken(){

    }
    @RequestMapping(value = "/savetoken",method = RequestMethod.GET)
    public String getAccessToken(HttpServletRequest request, HttpServletResponse response, Model model){
        // 1、查找出库里所有的记录，
        List< Wxuser > userlist = new ArrayList<Wxuser>();
        StringBuilder selectSql0 = new StringBuilder();
        selectSql0.append(" From Wxuser u where 1=1 ");

        userlist = dbService.getWxuserList( selectSql0.toString() );

        Wxuser s = userlist.get(0);

        Iterator it = userlist.iterator();
        while( it.hasNext() ){
            Wxuser wxuser = (Wxuser)it.next();
            AccessToken token = configService.getAccessToken(wxuser.getAppid(), wxuser.getAppsecret());
            String token1 = token.getAccessToken();
            wxuser.setAccessToken(token1);
            wxuser.setUpdatetime(new Date().getTime()/1000);
            dbService.updateUser(wxuser);
        }

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("1", formatter.format(currentTime));
        return jsonObject.toString();
    }
}
